package cn.muqingfeng.bbs.ui;

import java.util.HashMap;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
import cn.muqingfeng.api.RequestHelper;
import cn.muqingfeng.api.UriHelper;
import cn.muqingfeng.api.request.GsonRequest;
import cn.muqingfeng.api.to.LoginResponseTO;
import cn.muqingfeng.api.to.UserTO;
import cn.muqingfeng.bbs.R;
import cn.muqingfeng.bbs.constants.Constants;
import cn.muqingfeng.util.AccountManager;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;

public class LoginActivity extends BaseActivity implements OnClickListener {
	private static final Object LOGIN_LOCK = new Object();
	private static final int REQUEST_CODE_REGIST = 455;
	public static final int ACTION_RETURN = 200;
	private ProgressDialog mLoginDialog;
	private EditText mUsernameView;
	private EditText mPasswordView;
	private boolean isLogin = false;
	private int mAction = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		setupViews();
	}

	private void setupViews() {
		mAction = getIntent().getIntExtra(Constants.EXTRA_ACTION, -1);
		findViewById(R.id.back).setOnClickListener(this);
		findViewById(R.id.forget_pass).setOnClickListener(this);
		findViewById(R.id.regist).setOnClickListener(this);
		findViewById(R.id.login).setOnClickListener(this);
		mUsernameView = (EditText) findViewById(R.id.username);
		mPasswordView = (EditText) findViewById(R.id.password);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.forget_pass: {
			Intent intent = new Intent(this, FindPasswordAvtivity.class);
			startActivity(intent);
		}
			break;
		case R.id.regist: {
			Intent intent = new Intent(this, RegistActivity.class);
			startActivityForResult(intent, REQUEST_CODE_REGIST);
		}
			break;
		case R.id.login:
			login();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			return;
		}
		if (requestCode == REQUEST_CODE_REGIST) {
			finish();
		}
	}

	private void login() {
		synchronized (LOGIN_LOCK) {
			if (isLogin)
				return;
			String username = mUsernameView.getText().toString();
			if (TextUtils.isEmpty(username)) {
				Toast.makeText(getApplicationContext(), "请输入用户名", Toast.LENGTH_SHORT).show();
				return;
			}
			final String password = mPasswordView.getText().toString();
			if (TextUtils.isEmpty(password)) {
				Toast.makeText(getApplicationContext(), "请输入密码", Toast.LENGTH_SHORT).show();
				return;
			}
			isLogin = true;
			showDialog();
			String requestUrl = UriHelper.getLoginUrl();
			HashMap<String, String> params = new HashMap<String, String>();
			params.put(UriHelper.PARAMS_USERNAME, username);
			params.put(UriHelper.PARAMS_PASSWORD, password);
			GsonRequest<LoginResponseTO> request = new GsonRequest<LoginResponseTO>(Method.POST, requestUrl, new Listener<LoginResponseTO>() {

				@Override
				public void onResponse(LoginResponseTO response) {
					isLogin = false;
					if (!isDestroied()) {
						dismissDialog();
						if (response != null && response.isSuccess()) {
							UserTO userTo = response.getUser();
							if (userTo != null) {
								Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
								AccountManager.saveUser(getApplicationContext(), userTo);
								AccountManager.setPassword(getApplicationContext(), password);
								if(mAction == ACTION_RETURN){
									startActivity(new Intent(LoginActivity.this, AccountActivity.class));
								}else{
									setResult(RESULT_OK);
								}
								finish();

							} else {
								Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
						}
					}
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					isLogin = false;
					if (!isDestroied()) {
						dismissDialog();
						Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
					}
				}
			}, params, LoginResponseTO.class);
			RequestHelper.startRequest(getApplicationContext(), request);
		}

	}

	private void showDialog() {
		if (mLoginDialog != null && mLoginDialog.isShowing()) {
			return;
		}
		mLoginDialog = new ProgressDialog(this);
		mLoginDialog.setMessage("正在登录...");
		mLoginDialog.show();
	}

	private void dismissDialog() {
		if (mLoginDialog != null && mLoginDialog.isShowing()) {
			mLoginDialog.dismiss();
		}
	}
}
